package com.grm.distributed.lock.service;

import com.grm.distributed.lock.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * redisson解决超卖-可重入锁，拼的是运气(非公平锁)
 */
@Service
@Slf4j
public class ProductService11 {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    public Result sell() {
        // 获取锁
        RLock lock = redissonClient.getLock("lock");
        // 加锁
        lock.lock();
        try {
            // 1. 查询库存信息
            String stock = redisTemplate.opsForValue().get("product_count");
            // 2. 判断库存是否充足
            if (stock != null && stock.length() != 0) {
                Integer st = Integer.valueOf(stock);
                if (st > 0) {
                    // 3.扣减库存
                    st = st - 1;
                    log.info("product current count = {}", st);
                    redisTemplate.opsForValue().set("product_count", String.valueOf(st));
                }
            }
        } finally {
            // 解锁
            lock.unlock();
        }
        return Result.success();
    }
}
